package com.yazi.mxz.person.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.ckfinder.connector.configuration.ConfigurationPathBuilder;
import com.yazi.mxz.common.entity.enums.AccountType;

/**
 * 
 * @author mo_yq5
 * @date 2014-3-17
 */
public class CKFinderPathBuilder extends ConfigurationPathBuilder {

	@Override
	public String getBaseDir(HttpServletRequest req) {
		String attaType = req.getParameter("attaType");
		return MyConfig.getInstance().getUploadPath() + getPath(attaType);
	}

	@Override
	public String getBaseUrl(HttpServletRequest req) {
		String attaType = req.getParameter("attaType");
		return getPath(attaType);
	}

	private String getPath(String attaType) {
		Subject subject = SecurityUtils.getSubject();
		Principal pc = (Principal) subject.getPrincipal();
		Long memberId = null != pc.getMember() ? pc.getMember().getMemberId() : null;
		Long storeId = null != pc.getStore() ? pc.getStore().getStoreId() : null;
		Long companyId = null != pc.getCompany() ? pc.getCompany().getCompanyId() : null;
		String path = "/";
		/*
		 * 每达到1024用户、店铺、或者企业就分别重新归属到一个新目录
		 */
		if (attaType == null) {
			path += "m" + memberId / 1024 + "/" + memberId;
		} else if (attaType.equals(AccountType.STORE.name()) && null != storeId) {
			path += "s" + storeId / 1024 + "/" + storeId;
		} else if (attaType.equals(AccountType.COMPANY.name()) && null != companyId) {
			path += "f" + companyId / 1024 + "/" + companyId;
		} else {
			path += "m" + memberId / 1024 + "/" + memberId;
		}
		return path + "/";
	}

}
